import SchemaForm from '@/components/SchemaForm';
import { command, schema } from '@/ts/base';
import { ProFormColumnsType } from '@ant-design/pro-components';
import React, { useMemo, useRef, useState } from 'react';
import { ProFormInstance } from '@ant-design/pro-form';
import { EntityInput as _EntityInput } from '@/components/Common/EntityInput';
import OrgCtrl from '@/ts/controller';
import { AssignTaskModel } from '@/ts/core/thing/standard/assignTaskModel';
import { XAssignTask } from '@/ts/base/schema';
import { ReportTree } from '@/ts/core/thing/standard/reporttree/ReportTree';
import {
  DatePicker,
  DatePickerProps,
} from '@/components/Common/StringDatePickers/DatePicker';
import { PeriodType } from '@/ts/base/enum';
import orgCtrl from '@/ts/controller';
import message from '@/utils/message';

interface Iprops {
  formType: string;
  current: any;
  finished: () => void;
}
const EntityInput: any = _EntityInput;
/*
  编辑
*/
const ReportTaskForm = (props: Iprops) => {
  const [taskModel, setTaskModel] = useState<any>({});
  const [modelPeriodType, setModelPeriodType] = useState<PeriodType>(PeriodType.Any);
  let title = '新建任务';
  let initialValue: any = {};
  const formRef = useRef<ProFormInstance>();
  const createPeriodType = useMemo(() => {
    const attrs: DatePickerProps = {
      picker: 'date',
      format: 'YYYY-MM-DD',
    };
    switch (modelPeriodType) {
      case PeriodType.Year:
        attrs.picker = 'year';
        attrs.format = 'YYYY';
        break;
      case PeriodType.Quarter:
        attrs.picker = 'quarter';
        attrs.format = 'YYYY-MM';
        break;
      case PeriodType.Month:
        attrs.picker = 'month';
        attrs.format = 'YYYY-MM';
        break;
      case PeriodType.Week:
        attrs.picker = 'week';
        attrs.format = 'YYYY-MM-DD';
        break;
      case PeriodType.Day:
        attrs.picker = 'date';
        attrs.format = 'YYYY-MM-DD';
        break;
      default:
        attrs.picker = 'date';
        attrs.format = 'YYYY-MM-DD';
        break;
    }

    return <DatePicker {...attrs} />;
  }, [modelPeriodType]);

  const columns: ProFormColumnsType<schema.XAssignTask>[] = [
    {
      title: '任务模板',
      dataIndex: 'assignTaskModel',
      readonly: false,
      colProps: { span: 24 },
      formItemProps: {
        rules: [{ required: true, message: '任务模板为必填项' }],
      },
      renderFormItem: () => {
        return (
          <EntityInput
            readonly={false}
            typeName="任务模板"
            directory={OrgCtrl.user.directory}
            rootKey={'disk'}
            onValueChange={(file: any) => {
              if (file) {
                setTaskModel(file);
                const model = file as AssignTaskModel;
                setModelPeriodType(model.metadata.periodType);
              }
            }}
          />
        );
      },
    },
    {
      title: '分发类型',
      dataIndex: 'assignType',
      valueType: 'select',
      initialValue: 'all',
      fieldProps: {
        options: [
          {
            value: 'all',
            label: '全部分发',
          },
          {
            value: 'step',
            label: '逐级分发',
          },
        ],
      },
      formItemProps: {
        rules: [{ required: true, message: '分发类型为必填项' }],
      },
    },
    {
      title: '数据时期',
      dataIndex: 'period',
      valueType: 'date',
      readonly: false,
      formItemProps: {
        rules: [{ required: true, message: '数据时期为必填项' }],
      },
      renderFormItem: () => {
        return createPeriodType;
      },
    },
  ];
  return (
    <SchemaForm<schema.XAssignTask>
      formRef={formRef}
      open
      title={title}
      width={640}
      columns={columns}
      initialValues={initialValue}
      rowProps={{
        gutter: [24, 0],
      }}
      layoutType="ModalForm"
      onOpenChange={(open: boolean) => {
        if (!open) {
          props.finished();
        }
      }}
      onFinish={async (values) => {
        const assignTaskModel = taskModel as AssignTaskModel;
        const space = assignTaskModel.target;
        if (!space) {
          message.error('未获取到模板对应组织!');
          return;
        }
        if (!space.hasSuperAuth()) {
          message.error('您不是模板所在空间管理员!');
          return;
        }
        // 根据任务模板查询报表树
        const xReportTree = await assignTaskModel.loadReportTree();
        if (!xReportTree) {
          message.error('未获取到任务模板绑定的报表树!');
          return;
        }
        const reportTree = new ReportTree(xReportTree, space.directory);
        // 报表树根节点信息 + 表单信息创建任务
        const nodes = await reportTree.loadNodeById([xReportTree.rootNodeId]);
        if (!nodes || nodes.length < 1) {
          message.error('未获取到任务模板绑定的报表树!');
          return;
        }
        const assignTask = {
          ...nodes[0],
          period: values.period,
          assignType: values.assignType,
        } as XAssignTask;
        const task = await assignTaskModel.create(assignTask);
        if (!task) {
          message.error('创建任务失败!');
          return;
        }
        // 根据任务生成任务树，任务树根节点为传入的任务
        await reportTree.createAssignTree(task, space.directory);
        command.emitter('assign', 'refresh');
        props.finished();
      }}
    />
  );
};

export default ReportTaskForm;
